#-*- codeing = utf-8 -*-
#@Time : 2020/9/17 11:54
#@Author : 阳某
#@File : 淘宝.py
#@Software : PyCharm
import csv
import re
from lxml import etree
from selenium import webdriver
import time
from selenium.webdriver import ActionChains
from selenium.webdriver import ChromeOptions
def search(key):
    driver.get("https://www.taobao.com/")
    driver.find_element_by_id('q').send_keys(key)
    time.sleep(1)
    driver.find_element_by_class_name('btn-search').click()
    driver.implicitly_wait(10)  #隐示等待 10秒   等待页面渲染完之后就不在等待
    driver.maximize_window()    #最大化浏览器

    # #解决登录
    driver.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys('tb480426989')
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys('xxxxx')
    time.sleep(2)
    #  解决滑块
    """
            根据偏移量获取移动轨迹
            :param distance:偏移量
            :return:移动轨迹
            """
    # 需要滑动的距离
    distance = 258
    t = 0
    track = []
    current = 0
    mid = distance * t / (t + 1)
    v = 0
    while current < distance:
        if current < mid:
            a = 3
        else:
            a = -1
        v0 = v
        v = v0 + a * t
        move = v0 * t + 1 / 2 * a * t * t
        current += move
        track.append(round(move))
    login = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]')
    action = ActionChains(driver)
    action.click_and_hold(on_element= login)
    for i in track:
        action.move_by_offset(xoffset=i, yoffset=0).perform()
    time.sleep(0.5)
    action.release().perform()
    # action.move_by_offset(xoffset=258,yoffset=0)
    # action.pause(2).release().perform()   #pause表示多少时间内执行完，release表示释放鼠标，perform表示立即执行动作链
    driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()
    driver.implicitly_wait(10)

    # 获取总页数
    page = driver.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/div[1]').text
    page_num = re.findall('(\d+)',page)[0]

    return page_num

def get_data():
    # 用第三方lxml解析
    page_text = driver.page_source
    e = etree.HTML(page_text)
    div_list = e.xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div')
    for div in div_list:
        title = div.xpath('.//div[@class="row row-2 title"]//text()')
        price = div.xpath('.//div[@class="price g_price g_price-highlight"]//text()')
        nums = div.xpath('.//div[@class="deal-cnt"]//text()')
        shop_name = div.by_xpath('.//div[@class="shop"]//text()')
        shop_add = div.xpath('.//div[@class="location"]//text()')
        print(title, price, nums, shop_name ,shop_name, shop_add ,sep = '|')
        with open('../data.csv', 'a', encoding='utf-8-sig', newline='')as csvfile:
            csvwriter = csv.writer(csvfile,delimiter = ',')
            csvwriter.writerow([title, price, nums, shop_name ,shop_name, shop_add])    #传入序列化数据
def main():
    page = search(keyword)
    page_num = 1    #page_num*44
    while page_num != page:
        print('*'*100)
        print('正在打印第%s页'%(page_num))
        print('*'*100)
        # https://s.taobao.com/search?q=U盘&s=0  第一页
        # https://s.taobao.com/search?q=U盘&s=44  第二页
        driver.get('https://s.taobao.com/search?q={}&s={}'.format(keyword,(page_num-1) * 44))
        driver.implicitly_wait(10)
        get_data()
        page_num += 1
    driver.quit()
if __name__ == '__main__':
    option = ChromeOptions()
    option.add_experimental_option("excludeSwitches", ['enable-automation'])
    # 如何实现让selenium规避被检测的风险
    driver = webdriver.Chrome(options = option)
    keyword = input('请输入你要爬取的商品名称：')
    main()